const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors()); // 跨域中间件
app.use(express.json()) // 解析json中间件
app.use(express.urlencoded({ extended: true })); // 解析url编码中间件

const jwt = require('jsonwebtoken');
app.use((req, res, next) => { // 全局中间件,绑定全局错误提示res.cc
  res.cc = (err, code = 1) => {
    res.send({ code, error: err?.message || err });
  }


  // 解析token信息
  const token = req.headers?.authorization?.split(' ')[1];
  if (token) {
    req.user = jwt.verify(token, config.jwtSecretKey);
  }
  next()
})


const config = require('./config.js'); // 导入配置文件
const {expressjwt} = require('express-jwt'); // 导入身份认证中间件
 // 除/user外的接口都需要Authorization身份认证
app.use(expressjwt({ secret: config.jwtSecretKey, algorithms: ['HS256'] }).unless({ path: [ /^\/user/] }))



const user_route = require('./router/user.js'); // 导入路由模块
app.use('/user', user_route); // 挂载/user路由

const my_route = require('./router/userInfo.js')
app.use('/my', my_route) // 挂载/my路由

const article_route = require('./router/artcate.js')
app.use('/my/article', article_route)


const Joi = require('joi') // 表单校验中间件
// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.log('error---',err)
  if(!err)return
  if(err.name === 'UnauthorizedError') return res.cc('身份认证失败',401)
  if (err instanceof Joi.ValidationError) {
    res.cc(err)
  }
})

// 启动服务
app.listen(3001, () => {
  console.log('Server is running on port 3001');
});